package com.xj.socket.tcp.nio.client;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SocketClient {
	private final Logger log=Logger.getLogger(SocketClient.class);
	public final Object lock=new Object();
	private String ip=null;
	private int port=6188;
	private Selector selector=null;
	private SocketChannel channel=null;
	private boolean conn_succeed=false;
	public SocketClient(String ip,int port){
		this.ip=ip;
		this.port=port;
	}
	public void connection() throws IOException{
		this.selector=Selector.open();
		this.channel=SocketChannel.open();
		this.channel.configureBlocking(false);
		this.channel.connect(new InetSocketAddress(this.ip, this.port));
		this.channel.register(this.selector, SelectionKey.OP_CONNECT);
		this.accept();
	}
	private void accept() throws IOException{
		while(true){
			synchronized (lock) {}
			int i=this.selector.select();
			if(i<=0){
				continue;
			}
			Set<SelectionKey> selectedKeys=this.selector.selectedKeys();
			Iterator<SelectionKey> it= selectedKeys.iterator();
			while(it.hasNext()){
				SelectionKey key=it.next();
				it.remove();
				if(key.isConnectable()){
					if(this.channel.finishConnect()){
						log.info("连接上服务器...");
						this.conn_succeed=true;
						synchronized (lock) {
							this.selector.wakeup();
							this.channel.register(this.selector, SelectionKey.OP_READ);
						}
						
					}
				}else if(key.isReadable()){
					System.out.println("开始读...");
					SocketChannel sc=(SocketChannel)key.channel();
					ByteBuffer readBuffer= ByteBuffer.allocate(1024);
					byte [] dst=null;
					int size=0;
					while((size=sc.read(readBuffer))>0){
						readBuffer.flip();
						dst=new byte[size];
						readBuffer.get(dst);
						readBuffer.clear();
					}
					System.out.print("收到服务端发来的消息：");
					System.out.println(new String(dst,"utf-8"));
					key.interestOps(SelectionKey.OP_READ);
				}else if(key.isWritable()){
					System.out.println("开始写...");
					
					key.interestOps(SelectionKey.OP_READ);
				}
			}
		}
	}
	public int send(String msg) throws IOException{
		if(!this.conn_succeed){
			return -1;
		}
		String info=msg;
		byte [] w_byte=info.getBytes("utf-8");
		ByteBuffer writeBuffer=ByteBuffer.allocate(w_byte.length);
		writeBuffer.put(w_byte);
		writeBuffer.flip();
		int len=0;
		System.out.println("--------");
		//synchronized (lock) {
		//	System.out.println("=====");
			this.selector.wakeup();
			len= this.channel.write(writeBuffer);
		//}
		
		return len;
	}
	public static void main(String[] args) throws IOException, InterruptedException {
		final SocketClient sc=new SocketClient("127.0.0.1", 9090);
		new Thread(new Runnable() {
			public void run() {
				try {
					sc.connection();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		Thread.sleep(30000);
		sc.send(12+"");
		//System.out.println(sc.send("我是客户端..."));
		//sc.send("我是客户端2...");
		/*synchronized(sc){
			sc.wait();
		}*/
	}
}
